<?php


/**
 * Notes:
 * PROJECT_NAME : ERP v1.8 重构erp
 * User: 夏鱼儿<397072174@qq.com>
 * Date: 2023/12/27
 * Time: 14:56
 */

namespace app\service\middleware;

use Closure;
use think\facade\Cache;
use think\response\Json;

class LoginLimit
{
    /**
     * 限制登录次数
     * @param $request
     * @param Closure $next
     * @return mixed|Json
     */
    public function handle($request, Closure $next): mixed
    {
        $ip = $request->ip();
        $key = '_login_limit:' .$request->param("name"). $ip;
        $count = Cache::get($key) ?: 0;

        if ($count >= 5) {
            // 超过登录次数限制，直接返回错误响应
            return json(['code' => 1001, 'msg' => '登录次数过多，请稍后再试']);
        }

        // 继续处理请求
        $response = $next($request);

        // 更新登录次数计数器
        if ($response->getCode() == 200 && str_contains($request->pathinfo(), 'login')) {
            Cache::inc($key);
            Cache::expire($key, 60 * 30); // 限制单位时间为 15 分钟
        }

        return $response;
    }
}